package org.wanghong.gift.userdetailservice;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.wanghong.gift.domain.LoginUser;
import org.wanghong.gift.domain.Permission;
import org.wanghong.gift.exception.asserts.Assert;
import org.wanghong.gift.exception.statuCode.StatusCode;
import org.wanghong.gift.mapper.LoginUserMapper;
import org.wanghong.gift.mapper.PermissionMapper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private LoginUserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 加载数据库中的认证的用户的信息：用户名，密码，用户的权限列表
     * @param username: 该方法把username传入进来，
        我们通过username查询用户的信息(密码，权限列表等)
        然后封装成 UserDetails进行返回 ，交给security 。
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //User是security内部的对象，UserDetails的实现类 ，
        //用来封装用户的基本信息（用户名，密码，权限列表）
        //public User(String username, String password, Collection<? extends GrantedAuthority> authorities)

        
        List<LoginUser> loginUsers = userMapper.
                selectList(new EntityWrapper<LoginUser>()
                        .eq("username", username)
                        .or()
                        .eq("tel", username)
                        .or()
                        .eq("email", username)
                );

        Assert.assertListNotEmpty(loginUsers, StatusCode.CODE_400_CODE_USERNAME_OR_PASSWORD_ERROR);

        //模拟存储在数据库的用户的密码：123
        //String password = passwordEncoder.encode("123");
        LoginUser loginUser = loginUsers.get(0);
        String password = loginUser.getPassword();

        //查询用户的权限
        List<Permission> permission = permissionMapper
                .selectPermissionsByUserId(loginUser.getId());

        //用户的权限列表,暂时为空
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        permission.forEach(e->{
            System.out.println("用户："+loginUser.getUsername()+" 加载权限："+e.getSn());
            authorities.add(new SimpleGrantedAuthority(e.getSn()));
        });

       User user = new User (username,password, authorities);
        return user;
    }
}